#!/usr/bin/env node

/**
 * 数据库管理工具
 * 整合迁移、备份、恢复等数据库操作
 */

const DatabaseMigrator = require('./migrate');
const DatabaseBackup = require('./backup');
const readline = require('readline');

class DatabaseManager {
  constructor() {
    this.migrator = new DatabaseMigrator();
    this.backup = new DatabaseBackup();
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
  }

  async question(prompt) {
    return new Promise((resolve) => {
      this.rl.question(prompt, resolve);
    });
  }

  async confirmAction(message) {
    const answer = await this.question(`${message} (y/N): `);
    return answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';
  }

  async safeUp(targetMigration = null) {
    console.log('🔄 Safe Migration Up Process');
    console.log('============================');
    
    try {
      // 1. 创建迁移前备份
      console.log('\n1. Creating pre-migration backup...');
      await this.backup.preMigrationBackup();
      
      // 2. 显示待执行的迁移
      await this.migrator.connect();
      const allMigrations = this.migrator.getMigrationFiles();
      const executedMigrations = await this.migrator.getExecutedMigrations();
      const pendingMigrations = allMigrations.filter(migration => 
        !executedMigrations.includes(migration)
      );
      
      if (pendingMigrations.length === 0) {
        console.log('\n✅ No pending migrations to execute');
        return;
      }
      
      console.log('\n2. Pending migrations:');
      pendingMigrations.forEach((migration, index) => {
        console.log(`   ${index + 1}. ${migration}`);
      });
      
      // 3. 确认执行
      const confirmed = await this.confirmAction('\nProceed with migration?');
      if (!confirmed) {
        console.log('Migration cancelled');
        return;
      }
      
      // 4. 执行迁移
      console.log('\n3. Executing migrations...');
      await this.migrator.up(targetMigration);
      
      console.log('\n✅ Safe migration completed successfully!');
      
    } catch (error) {
      console.error('\n❌ Migration failed:', error.message);
      console.log('\n🔄 You can restore from the pre-migration backup if needed.');
      
      const backups = this.backup.listBackups();
      const preMigrationBackups = backups.filter(b => b.filename.includes('pre_migration'));
      
      if (preMigrationBackups.length > 0) {
        console.log(`\nLatest pre-migration backup: ${preMigrationBackups[0].filename}`);
        const shouldRestore = await this.confirmAction('Restore from backup?');
        
        if (shouldRestore) {
          await this.backup.restore(preMigrationBackups[0].filename);
          console.log('✅ Database restored from backup');
        }
      }
      
      throw error;
    } finally {
      await this.migrator.close();
    }
  }

  async safeDown(steps = 1) {
    console.log('🔄 Safe Migration Down Process');
    console.log('==============================');
    
    try {
      // 1. 创建回滚前备份
      console.log('\n1. Creating pre-rollback backup...');
      await this.backup.backup(this.backup.generateBackupFilename('pre_rollback'));
      
      // 2. 显示将要回滚的迁移
      await this.migrator.connect();
      const executedMigrations = await this.migrator.getExecutedMigrations();
      
      if (executedMigrations.length === 0) {
        console.log('\n✅ No migrations to rollback');
        return;
      }
      
      const migrationsToRollback = executedMigrations.slice(-steps).reverse();
      
      console.log('\n2. Migrations to rollback:');
      migrationsToRollback.forEach((migration, index) => {
        console.log(`   ${index + 1}. ${migration}`);
      });
      
      // 3. 确认回滚
      const confirmed = await this.confirmAction('\nProceed with rollback?');
      if (!confirmed) {
        console.log('Rollback cancelled');
        return;
      }
      
      // 4. 执行回滚
      console.log('\n3. Executing rollback...');
      await this.migrator.down(steps);
      
      console.log('\n✅ Safe rollback completed successfully!');
      
    } catch (error) {
      console.error('\n❌ Rollback failed:', error.message);
      console.log('\n🔄 You can restore from the pre-rollback backup if needed.');
      throw error;
    } finally {
      await this.migrator.close();
    }
  }

  async deploymentPipeline() {
    console.log('🚀 Deployment Pipeline');
    console.log('======================');
    
    try {
      // 1. 创建部署前备份
      console.log('\n1. Creating pre-deployment backup...');
      await this.backup.preDeploymentBackup();
      
      // 2. 检查迁移状态
      console.log('\n2. Checking migration status...');
      await this.migrator.connect();
      await this.migrator.status();
      
      const allMigrations = this.migrator.getMigrationFiles();
      const executedMigrations = await this.migrator.getExecutedMigrations();
      const pendingMigrations = allMigrations.filter(migration => 
        !executedMigrations.includes(migration)
      );
      
      if (pendingMigrations.length > 0) {
        console.log('\n⚠️  Pending migrations detected!');
        const shouldMigrate = await this.confirmAction('Run pending migrations?');
        
        if (shouldMigrate) {
          console.log('\n3. Executing pending migrations...');
          await this.migrator.up();
        } else {
          console.log('\n⚠️  Deployment cancelled - pending migrations not executed');
          return;
        }
      } else {
        console.log('\n✅ All migrations are up to date');
      }
      
      console.log('\n✅ Deployment pipeline completed successfully!');
      console.log('\n📋 Post-deployment checklist:');
      console.log('   - Verify application functionality');
      console.log('   - Check logs for any errors');
      console.log('   - Monitor system performance');
      console.log('   - Validate data integrity');
      
    } catch (error) {
      console.error('\n❌ Deployment pipeline failed:', error.message);
      console.log('\n🔄 Consider restoring from pre-deployment backup');
      throw error;
    } finally {
      await this.migrator.close();
    }
  }

  async healthCheck() {
    console.log('🏥 Database Health Check');
    console.log('========================');
    
    try {
      // 1. 连接测试
      console.log('\n1. Testing database connection...');
      await this.migrator.connect();
      console.log('   ✅ Database connection successful');
      
      // 2. 迁移状态检查
      console.log('\n2. Checking migration status...');
      const allMigrations = this.migrator.getMigrationFiles();
      const executedMigrations = await this.migrator.getExecutedMigrations();
      const pendingMigrations = allMigrations.filter(migration => 
        !executedMigrations.includes(migration)
      );
      
      console.log(`   Total migrations: ${allMigrations.length}`);
      console.log(`   Executed: ${executedMigrations.length}`);
      console.log(`   Pending: ${pendingMigrations.length}`);
      
      if (pendingMigrations.length > 0) {
        console.log('   ⚠️  Warning: Pending migrations detected');
      } else {
        console.log('   ✅ All migrations are up to date');
      }
      
      // 3. 备份状态检查
      console.log('\n3. Checking backup status...');
      const backups = this.backup.listBackups();
      
      if (backups.length === 0) {
        console.log('   ⚠️  Warning: No backups found');
      } else {
        const latestBackup = backups[0];
        const backupAge = Date.now() - latestBackup.created.getTime();
        const hoursOld = Math.floor(backupAge / (1000 * 60 * 60));
        
        console.log(`   Latest backup: ${latestBackup.filename}`);
        console.log(`   Age: ${hoursOld} hours old`);
        
        if (hoursOld > 24) {
          console.log('   ⚠️  Warning: Latest backup is over 24 hours old');
        } else {
          console.log('   ✅ Recent backup available');
        }
      }
      
      console.log('\n✅ Health check completed');
      
    } catch (error) {
      console.error('\n❌ Health check failed:', error.message);
      throw error;
    } finally {
      await this.migrator.close();
    }
  }

  close() {
    this.rl.close();
  }
}

// CLI 接口
async function main() {
  const command = process.argv[2];
  const arg = process.argv[3];

  const manager = new DatabaseManager();

  try {
    switch (command) {
      case 'safe-up':
        await manager.safeUp(arg);
        break;
      case 'safe-down':
        const steps = parseInt(arg) || 1;
        await manager.safeDown(steps);
        break;
      case 'deploy':
        await manager.deploymentPipeline();
        break;
      case 'health':
        await manager.healthCheck();
        break;
      default:
        console.log('Database Manager');
        console.log('================');
        console.log('Usage:');
        console.log('  node db-manager.js safe-up [target]   - Safe migration up with backup');
        console.log('  node db-manager.js safe-down [steps]  - Safe migration down with backup');
        console.log('  node db-manager.js deploy             - Full deployment pipeline');
        console.log('  node db-manager.js health             - Database health check');
        console.log('');
        console.log('Individual tools:');
        console.log('  node migrate.js <command>             - Migration operations');
        console.log('  node backup.js <command>              - Backup operations');
        break;
    }
  } catch (error) {
    console.error('Operation failed:', error.message);
    process.exit(1);
  } finally {
    manager.close();
  }
}

if (require.main === module) {
  main();
}

module.exports = DatabaseManager;